package org.xdq.代理模式;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Utils {

    public static <T> T getInviterProxy(Class targetClass,Class<T> proxyInterfaceClass,BeforeAfterAction action) throws IllegalAccessException, InstantiationException {

        Object target = targetClass.newInstance();//目标对象

        Object proxyObj =
            Proxy.newProxyInstance(
                    targetClass.getClassLoader(),
                    new Class[]{proxyInterfaceClass},
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            action.before();
                            Object rel = method.invoke(target,args);//执行目标对象的方法,args是目标对象方法的参数
                            action.after();
                            return rel;
                        }
                    }
            );

        return (T)proxyObj;
    }


}
